package tech.aistar.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletRequest request) {
        return userService.login(username,password,  request);
    }

    @RequestMapping(value = "/userInfo")
    public String userInfo(HttpServletRequest request, Model model) {
        User userSession = (User) request.getSession().getAttribute("userSession");
        model.addAttribute("userInfo", userSession);
        return "my-account";
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public Result register(String username, String password, String email,String name) {
        return userService.register(username,password,  email,name);
    }

    @RequestMapping(value = "/updatePwd")
    @ResponseBody
    public Result updatePwd(String oldPassword,String newPassword,String confirmPassword,HttpServletRequest request) {
        User userSession = (User) request.getSession().getAttribute("userSession");
        if (!userSession.getPassword().equals(oldPassword)) {
            return new Result("400", "密码不正确", null);
        }
        return userService.updatePassword(oldPassword, newPassword, confirmPassword,userSession);
    }

    @RequestMapping(value = "/loginOut")
    public String loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        return "login";
    }

}

